var frameRate = 0;
var canvas;
var lastTime;

var mySprite;
var spriteRotation = 0;

var xpos = 0;
var ypos = 425;

var upPressed;
var upLocked;
var upFirst;
var downPressed;
var downLocked;
var rightPressed;
var rightLocked;
var leftPressed;
var leftLocked;
var actionButton1;
var actionButton1Locked;
var direction;
var onGround = true;

$(document).ready(function() {
    init(20);
});

    function init(fps) {
        // Initialize variables
	upPressed=false;
	upLocked=false;
	upFirst=false;
	rightPressed=false;
	rightLocked=false;
	downPressed=false;
	downLocked=false;
	leftPressed=false;
	leftLocked=false;
	actionButton1=false;
	actionButton1Locked=false;

        // Get the canvas element using the DOM
        canvas = document.getElementById('mycanvas');

        // Make sure we don't execute when canvas isn't supported
        if (canvas.getContext){
                    // Use getContext to use the canvas for drawing
                    ctx = canvas.getContext('2d');

                    frameRate = fps;

                    // Initialize game, before game start to call updates
                    // This is function which you need to make every game!
                    initGame();

                    // We need to initialize lastTime, so we don't get false delta value on first update
                    lastTime = new Date().getTime();
                    //fw_update();
                    //renderScene(1.0);
                    if (fps > 0) {
                            timeInterval = 1000 / fps;
                            // timer calls fw_update function as often we want
                            setInterval(fw_update, timeInterval);
                    } else {
                            // if we don't have timer, we update once our framework
                            fw_update();
                    }

                    // Setup events
                    bindEvents();
        } else {
                    alert('You need HTML5 compatible browser to see this demo!');
        }
    }

    function bindEvents() {
        $(document).keydown(function(event) {onKeyDown(event)});
        $(document).keyup(function(event) {onKeyUp(event)});
    }

    function fw_update()
    {
            // we update time
            var currTime = new Date().getTime();
            // and calculate time of between two frames
            var delta = (currTime - lastTime) / 1000.0;
            // we need to remember previous time
            lastTime = currTime;

            // we don't accept too big delta values
            if (delta > 1.0) delta = 1.0;
//            if (rightPressed||leftPressed||upPressed) {
                // update game logic
                updateScene(delta);
                // render game
                renderScene(delta);
//            }
    }

    function keyPressed() {
        return (leftPressed||rightPressed||upPressed);
    }

    function initGame()
    {
            // load all game images here
            myBackground = loadSprite("assets/mountain-background.jpg");
            mySprite = loadSprite("assets/sprite.png");
            mySprite2 = loadSprite("assets/mario_sprites_nobg.png");
    }

    function updateScene(delta)
    {            
            // rotation speed 45 degrees/second.
            spriteRotation += (Math.PI / 180.0) * 45 * delta;
            if (leftPressed && xpos >= 2 ) {
                xpos -= SPEED;
            } else if(rightPressed && xpos < canvas.width - 32 ) {
                xpos += SPEED;
            }

            if(upPressed && !upLocked) {
                ypos = canvas.height - 45 - JUMP;
                upLocked = true;
            }

            onGround = (ypos+45 == 395 && xpos >= 400 && xpos <= 450);
            if (ypos == 395+45 && xpos >= 400 && xpos <= 450) {
                ypos = 395;
                onGround = true;
            }

            if (!onGround && ypos < (canvas.height-60)) {
                ypos+=15;
            } else {
                upLocked = false;
            }
    }

    function renderScene(delta)
    {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(myBackground, 0, 0, 640, 480, 0, 0, 640, 480);

            ctx.moveTo(400, 395);
            ctx.lineTo(450, 395);
            ctx.strokeStyle = "#FF0FF";
            ctx.stroke();

            if (xpos == 0) a = 1; else a = 1;
            x = 2 + (((xpos/2)%4) * 30);
            if (direction == "left") y = 45; else y = 0;
            ctx.drawImage(mySprite2, x, y, 28, 45, xpos, ypos, 30, 45);

//            ctx.drawImage(mySprite2, 32, y, 28, 45, xpos, ypos-100, 28, 45);
//            ctx.drawImage(mySprite2, 62, y, 28, 45, xpos, ypos-200, 28, 45);
//            ctx.drawImage(mySprite2, 89, y, 28, 45, xpos, ypos-300, 28, 45);
//            ctx.drawImage(mySprite2, 89, y, 30, 45, xpos, ypos-400, 30, 45);
            //console.log(xpos);
    }

    // [imageName] image file name
    function loadSprite(imageName)
    {
        // create new image object
        var image = new Image();
        // load image
        image.src = imageName;
        // return image object
        return image;
    }

    // [imageObject] this is image object which is returned loadImage
    // [x] screen x coordinate
    // [y] screen y coordinate
    // [rotation] rotation angle in radians (normal value 0.0)
    // [scale] sprite scale (normal value 1.0)
    function drawSprite(imageObject, x, y, rotation, scale)
    {
        var w = imageObject.width;
        var h = imageObject.height;

        // save state
        ctx.save();
        // set screen position
        ctx.translate(x, y);
        // set rotation
        ctx.rotate(rotation);
        // set scale value
        ctx.scale(scale, scale);
        // draw image to screen drawImage(imageObject, sourceX, sourceY, sourceWidth, sourceHeight,
        // destinationX, destinationY, destinationWidth, destinationHeight)
        ctx.drawImage(imageObject, 0, 0, w, h, -w/2, -h/2, w, h);
        //ctx.drawImage(imageObject, 100, 0, w, h, -w/2, -h/2, w, h);
        // restore state
        ctx.restore();
    }

    function drawLine(xs, ys, xe, ye, c) {
        ctx.lineWidth = 5;
        ctx.beginPath();
        ctx.strokeStyle = c;
        ctx.moveTo(xs, ys);
        ctx.lineTo(xe, ye);
        ctx.stroke();
    }

function onKeyDown(evt){
	switch (evt.keyCode) {
		case 38: if (!upLocked) upPressed=true; else upPressed=false; break;
		case 40: downPressed=true; break;
		case 37: leftPressed=true; direction="left"; break;
		case 39: rightPressed=true; direction="right"; break;
		case 90: actionButton1=true; break; // z
	}
}


function onKeyUp(evt){
	switch (evt.keyCode) {
		case 38:
			upPressed=false;
			//upLocked=false;
//                        ypos += 20;
                        //updateScene(1);
                        //renderScene(1);
		break;

		case 40:
			downPressed=false;
			downLocked=false;
		break;

		case 37:
			leftPressed=false;
			leftLocked=false;
		break;

		case 39:
			rightPressed=false;
			rightLocked=false;
		break;

		case 90: // z
			actionButton1=false;
			actionButton1Locked=false;
		break;
	}
}